package  
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Stage;
	import flash.events.Event;
	import systems.EventChannel;
	import systems.events.BulletEvent;
	import systems.events.EnemyEvent;
	import systems.events.ShipEvent;
	
	/**
	 * @author Humberto Anjos
	 */
	public class GameWorld 
	{
		private var _ship:Ship
		private var _bullets = []
		private var _enemies = []
		private var _all = []
		
		public function GameWorld() 
		{ 
			start()
		}
		
		public function newShip(state:String, x:int, y:int)
		{
			_ship = new Ship(this, state, x, y)
			_all.push(_ship)
			
			EventChannel.INSTANCE.dispatchEvent(new ShipEvent(ShipEvent.SHIP_CREATED, _ship))
		}
		
		public function destroyShip()
		{
			var corpse:Ship = _ship
			_all.splice(_all.indexOf(corpse), 1)
			
			EventChannel.INSTANCE.dispatchEvent(new ShipEvent(ShipEvent.SHIP_DESTROYED, corpse))
		}
		
		public function newBullet(state:String, x:int, y:int):void
		{
			var bullet:Bullet = new Bullet(state, x, y)
			_bullets.push(bullet)
			_all.push(bullet)
			
			EventChannel.INSTANCE.dispatchEvent(new BulletEvent(BulletEvent.BULLET_CREATED, bullet))
		}
		
		public function destroyBullet(bullet:Bullet):void
		{
			_bullets.splice(_bullets.indexOf(bullet), 1)
			_all.splice(_all.indexOf(bullet), 1)
			
			EventChannel.INSTANCE.dispatchEvent(new BulletEvent(BulletEvent.BULLET_DESTROYED, bullet))
		}
		
		public function newEnemy(state:String, x:int, y:int):void 
		{
			var enemy = new Enemy(state, x, y)
			_enemies.push(enemy)
			_all.push(enemy)
			
			EventChannel.INSTANCE.dispatchEvent(new EnemyEvent(EnemyEvent.ENEMY_CREATED, enemy))
		}
		
		public function destroyEnemy(enemy:Enemy):void
		{
			_enemies.splice(_enemies.indexOf(enemy), 1)
			_all.splice(_all.indexOf(enemy), 1)
			
			EventChannel.INSTANCE.dispatchEvent(new EnemyEvent(EnemyEvent.ENEMY_DESTROYED, enemy))
		}
		
		public function update()
		{
			if (_ship != null)
			{
				_ship.update()
			}
			
			for each(var bullet:Bullet in _bullets)
			{
				bullet.update()
			}
			
			for each(var enemy:Enemy in _enemies)
			{
				enemy.update()
			}
		}
		
		public function start()
		{
			_bullets = []
			_enemies = []
			_all = []
		}
		
		public function clear()
		{
			_ship = null
			_bullets.length = 0
			_enemies.length = 0
			_all.length = 0
		}
		
		// properties
		public function get objects():Array { return _all }
		public function get enemies():Array { return _enemies }
		public function get bullets():Array { return _bullets }
		public function get ship():Ship { return _ship }
	}

}